<?php

namespace App\Http\Controllers\Api\Post;

use App\Http\Controllers\Controller;
use App\Models\Posts;
use App\Models\PostsComment;
use App\Models\PostsLikes;
use App\Models\Users;
use Illuminate\Support\Facades\DB;
use App\Models\OrganizationsMembers;
use Illuminate\Http\Request;

class PostController extends Controller
{
    /**
     * 帖子列表
     *
     * @return array
     */
    public function lists(): array
    {
        $where = [
            'status'=>1
        ];
        $data = Posts::query()->where($where)->oldest('sort')->get();
        $result = array();
        if($data){
            foreach ($data as$val){
                $result[] = Posts::getDataByID($val['id']);
            }
        }
        return ret($result);
    }

    /***
     * @return mixed
     * 组织下的帖子
     */
    public function listByorg(): array
    {

        $post = request()->only('organizations_id');
        if(empty($post['organizations_id'])){
            return retError('缺少组织ID');
        }
        //$user = auth('api')->user();
        $where = [
            'status'=>1,
            'organizations_id'=>$post['organizations_id']
        ];
        $data = Posts::query()->where($where)->oldest('sort')->get();
        $result = array();
        if($data){
            foreach ($data as$val){
                $result[] = Posts::getDataByID($val['id']);
            }
        }
        return ret($result);
    }

/***
 * @return mixed
 *
 * 申请贴子
 */
    public function addOrgPost(): array
    {

        $post = request()->only('title','content','contact_phone','organizations_id','image');
        if(empty($post['organizations_id'])){
            return retError('缺少组织ID');
        }
        $user = auth('api')->user();


        $post['user_id'] = $user['id'];
        $post['username'] = $user['username'];

        DB::beginTransaction();
        try {

            $checkAdmin = OrganizationsMembers::query()->where([
                ['organization_id', '=', $post['organizations_id'] ],
                ['is_admin', '=',1],
                ['user_id', '=',$user['id']]
            ])->first();

            if($checkAdmin){

                Posts::query()->create($post);
            }else{
                return retError('权限不足');
            }

            DB::commit();
            return ret('操作成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }


    }

    /**
     * 帖子详情
     * @return array
     */
    public function detail(): array
    {
        $id = request('id',null);
        $return =array();
        $info = Posts::getDataByID($id);
        if($info){

            $where = array();
            $where['post_id']  = $info['id'];
            $where['type']  = 2;
            $where['status']  = 2;
          //$list =   PostsComment::query()->where($where)->with(['userLike'])->latest()->get();

            $page = request('page',1);    //页数
            $limit =  request('limit',10);  //每页显示条数
            $offset = ($page - 1) * $limit; //偏移量


            $count = PostsComment::query()
                ->where($where)
                ->count();


            $data =  PostsComment::getList($where,$offset,$limit,'id');


            $total_pages = ceil(($count + $page-1) / $limit);


            $result = array();
            $return = array();
            if($data){
                foreach ($data as$val){
                    $result[] = PostsComment::formatListData($val);  //Users::getDataByID($val['id']);
                }
            }

            // 通过组织ID  去判断是否是否为管理员
            $user = auth('api')->user();
            $where = array();
            $where['organization_id'] = $info['organizations_id'];
            $where['is_admin'] = 1;
            $where['user_id'] = $user['id'];
            $base_info = OrganizationsMembers::query()->where($where)->first();
            if( !empty($base_info) ){   // 发送图片只有管理员才有权限
                $info['is_admin'] = 1;
            }else{
                $info['is_admin'] = 0;
            }

            $return['info'] = $info;
            $return['data'] = $result;
            $return['count'] = $count;
            $return['page'] = $page;
            $return['total_pages'] = $total_pages;

        }

        return ret($return);
    }

    /**
     * 帖子详情
     * @return array
     */
    public function commentDetail(): array
    {
        $id = request('id',null);

        $return =array();
        $info = Posts::getDataByID($id);
        if($info){

            $where = array();
            $where['post_id']  = $info['id'];
            $where['type']  = 1;
            $where['status']  = 2;

            $page = request('page',1);    //页数
            $limit =  request('limit',10);  //每页显示条数
            $offset = ($page - 1) * $limit; //偏移量


            $count = PostsComment::query()
                ->where($where)
                ->count();


            $data =  PostsComment::getList($where,$offset,$limit,'id');


            $total_pages = ceil(($count + $page-1) / $limit);


            $result = array();
            $return = array();
            if($data){
                foreach ($data as$val){
                    $result[] = PostsComment::formatListData($val);  //Users::getDataByID($val['id']);
                }
            }

            //$return['info'] = $info;
            $return['data'] = $result;
            $return['count'] = $count;
            $return['page'] = $page;
            $return['total_pages'] = $total_pages;

        }

        return ret($return);
    }

    /**
     * 帖子点赞
     * @return array
     */
    public function like(): array
    {
        $user = auth('api')->user();
        $post_id = request('post_id');
        if(!$post_id){
            return retError('帖子ID不能为空');
        }
        $comment_id = request('comment_id');
        if(!$comment_id){
            return retError('图片ID不能为空');
        }
        $user_id = $user->id;
        $where = [
            'comment_id'=>$comment_id,
            'user_id'=>$user_id,
            'post_id'=>$post_id
        ];
        $post_like = PostsLikes::query()->where($where)->count('id');

        DB::beginTransaction();
        try {
            if($post_like <=0){
                $create = [
                    'user_id'=>$user_id,
                    'username'=>$user->username,
                    'avatar'=>$user->avatar,
                    'post_id'=>$post_id,
                    'comment_id'=>$comment_id,
                ];
                PostsLikes::query()->create($create);

            }else{
               // Posts::query()->where('id',$post_id)->decrement('likes_counts');
                PostsLikes::query()->where($where)->delete();
            }
            DB::commit();
            return ret('操作成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }
    }

    /**
     * 我的帖子
     *
     * @return array
     */
    public function mine(): array
    {
        $user_id = auth('api')->id();
     //   $data = PostsLikes::query()->where('user_id',$user_id)->with('post')->get();
        $data = Posts::query()->where('user_id',$user_id)->get();

        $result = array();
        if($data){
            foreach ($data as $val){
             //   $result[] = Posts::getDataByID($val['post']['id']);
                $result[] = Posts::getDataByID($val['id']);
            }
        }
        return ret($result);
    }


    /***
     * @return mixed
     *
     * 申请贴子
     */
    public function addPostComment(): array
    {

        $post = request()->only('post_id','comment','image','type');
        if(empty($post['post_id'])){
            return retError('缺少帖子ID');
        }
        $user = auth('api')->user();

        //首先获取帖子的组织id
        $result = Posts::query()->where(['id'=>$post['post_id']])->first();
        if(empty($result) ){
            return retError('主帖不存在');
        }

        if(empty($user['is_alumni']) || $user['is_alumni'] != 2){
            return retError('用户未认证');
        }

        // 通过组织ID  去判断是否是否为管理员
        $where = array();
        $where['organization_id'] = $result['organizations_id'];
        $where['is_admin'] = 1;
        $where['user_id'] = $user['id'];
        $base_info = OrganizationsMembers::query()->where($where)->first();
        if(empty($base_info) && !empty($post['image'])){   // 发送图片只有管理员才有权限
            return retError('权限不足');
        }


        $post['user_id'] = $user['id'];
        $post['username'] = $user['username'];
        $post['status'] = 1;

        DB::beginTransaction();
        try {
            if(!empty($post['image'] &&  strpos($post['image'], ',') !== false ))
            {
                   $imageArray =  explode(',',$post['image']);
                    foreach($imageArray as $val){
                        unset($post['image']);
                        $post['image'] = $val;
                        PostsComment::query()->create($post);
                    }
            }else{

                PostsComment::query()->create($post);
            }

            DB::commit();
            return ret('操作成功!');
        } catch (\Exception $e) {
            DB::rollBack();
            return retError($e->getMessage());
        }


    }


    public function menuPostComment(Request $request) :array
    {

        $return = array();

        $return[0]['name'] =  '评论';
        $return[0]['type'] =  '1';

        $return[1]['name'] =  '图片';
        $return[1]['type'] =  '2';
        return ret($return);
    }

    public function failPostComment() :array
    {

        $user_id = auth('api')->id();
        $where = array();
        $where['user_id']  = $user_id;
        $where['type']  = 1;
       // $where['status']  = array('in',[2,3]);
       // $where['status']  = 3;
        $list =   PostsComment::query()->where($where)->whereIn('status',[2,3])->latest('id')->get();
        $result = array();
        foreach($list as $key=>$val){

            $result[] = PostsComment::getDataByIDorg($val);
        }

        Users:: query()->where('id',$user_id)->update(['is_unread_review'=>0]);

        return ret($result);

    }
}
